package top.wilsonlv.jaguar.cloud.upms.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.wilsonlv.jaguar.basecrud.BaseService;
import top.wilsonlv.jaguar.cloud.upms.controller.vo.UserDeviceVO;
import top.wilsonlv.jaguar.cloud.upms.entity.Device;
import top.wilsonlv.jaguar.cloud.upms.entity.UserDevice;
import top.wilsonlv.jaguar.cloud.upms.mapper.UserDeviceMapper;

import java.util.Map;


/**
 * <p>
 * 用户设备 服务实现类
 * </p>
 *
 * @author lvws
 * @since 2022-01-13
 */
@Service
@RequiredArgsConstructor
public class UserDeviceService extends BaseService<UserDevice, UserDeviceMapper> {

    private final DeviceService deviceService;


    public UserDevice getByUserIdAndDeviceId(Long userId, Long deviceId) {
        return this.unique(Wrappers.lambdaQuery(UserDevice.class)
                .eq(UserDevice::getUserId, userId)
                .eq(UserDevice::getDeviceId, deviceId));
    }

    public UserDeviceVO getDetail(Long id) {
        UserDevice userDevice = this.getById(id);
        return userDevice.toVo(UserDeviceVO.class);
    }

    @Transactional
    public Page<UserDeviceVO> queryUserDevice(Page<UserDevice> page, Map<String, Object> params) {
        return this.mapper.queryUserDevice(page, params);
    }

    public Page<UserDeviceVO> rightJoinUserPage(Page<UserDevice> page, Map<String, Object> params) {
        return this.mapper.rightJoinUserPage(page, params);
    }

    @Transactional
    public void bindUserDevice(Long userId, Long deviceId) {
        UserDevice userDevice = this.unique(Wrappers.lambdaQuery(UserDevice.class)
                .eq(UserDevice::getUserId, userId)
                .eq(UserDevice::getDeviceId, deviceId));
        if (userDevice == null) {
            userDevice = new UserDevice();
            userDevice.setUserId(userId);
            userDevice.setDeviceId(deviceId);
            this.insert(userDevice);
        }
    }

    @Transactional
    public void unbindDevice(Long userId, String deviceUid) {
        Device device = deviceService.getByDeviceUid(deviceUid);
        if (device == null) {
            return;
        }

        UserDevice userDevice = this.getByUserIdAndDeviceId(userId, device.getId());
        if (userDevice == null) {
            return;
        }

        this.delete(userDevice.getId());
    }


}
